﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Newtonsoft.Json.Linq;

namespace ShopayServer.Http
{
    public class Response: IDisposable
    {
        public HttpListenerResponse response;

        private string content = "{}";
        private string contentType = "application/json;charset=utf-8";
        private int statusCode = 404;

        public Response(HttpListenerResponse response)
        {
            this.response = response;
        }

        public Response json(JToken json)
        {
            return setContent(json.ToString());
        }

        public Response setContent(string content)
        {
            this.statusCode = 200;
            this.content = content;

            return this;
        }

        // 发送至客户端
        public void send()
        {
            // 转化字节集
            byte[] content = Encoding.UTF8.GetBytes(this.content);

            response.ContentEncoding = Encoding.UTF8;
            response.StatusCode = statusCode;
            response.ContentType = contentType;
            response.ContentLength64 = content.Length;

            // 打开输出流
            System.IO.Stream stream = response.OutputStream;
            stream.Write(content, 0, content.Length);

            // 释放
            stream.Close();
            response.Close();
        }

        public void Dispose()
        {
            content = null;

            GC.SuppressFinalize(this);
        }
    }
}
